package com.leo.manage_system.controller;

import com.leo.manage_system.entity.Picture;
import com.leo.manage_system.entity.vo.WangPicture;
import com.leo.manage_system.service.PictureService;
import com.leo.manage_system.utils.JwtUtils;
import com.leo.manage_system.utils.R;
import com.leo.manage_system.utils.WangR;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.UUID;

@Api(tags = "文件管理")
@CrossOrigin //跨域
@RestController
@RequestMapping("/service_manage/file")
public class FileController {
    @Autowired
    PictureService pictureService;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");

    @ApiOperation("上传文件[管理员]")
    @PostMapping("/upload")
    public WangR upload(MultipartFile file) {
        String path = System.getProperty("user.dir");
        String absolutePath = path + "/uploadFiles/";
        String relativePath = "/uploadFiles/";
        WangR r = new WangR();
        String oldName = file.getOriginalFilename();
        assert oldName != null;
        String fileType = oldName.substring(oldName.lastIndexOf("."));
        File folder;
        // 根据文件类型创建对应文件夹
        System.out.println(fileType);
        if (fileType.equals(".jpg") || fileType.equals(".png")) {
            absolutePath += "Img/";
            relativePath += "Img/";
        } else if (fileType.equals(".mp4")) {
            absolutePath += "Video/";
            relativePath += "Video/";
        } else {
            r.setErrno(1);
            return r;
        }
        folder = new File(absolutePath);
        if (!folder.isDirectory()) {
            if (!folder.mkdirs()) {
                r.setErrno(2);
                return r;
            }
        }
        String newName = UUID.randomUUID() + oldName.substring(oldName.lastIndexOf("."));
        try {
            file.transferTo(new File(folder, newName));
            WangPicture pic = new WangPicture();
            pic.setUrl(relativePath + newName);
            r.setErrno(0);
            r.getData().add(pic);
            pictureService.save(new Picture().setUrl(relativePath + newName));
            return r;
        } catch (IOException e) {
            e.printStackTrace();
        }
        r.setErrno(3);
        return r;
    }
}
